package com.zking.seckillpro.config;

import com.zking.seckillpro.exception.BusinessException;
import com.zking.seckillpro.model.User;
import com.zking.seckillpro.service.IRedisService;
import com.zking.seckillpro.util.CookieUtils;
import com.zking.seckillpro.util.JsonResponseStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义参数解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IRedisService redisService;
    /**
     * supportsParameter方法所返回的ture或者false将会决定resolveArgument执不执行
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return User.class==methodParameter.getParameterType();
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //将nativewebrequest转换成httpServletRequest
        HttpServletRequest req= (HttpServletRequest) nativeWebRequest.getNativeRequest();
        //通过request对象获取cookie中的token对象
        String token = CookieUtils.getCookieValue(req, "token");
        //判断token是否为空
        if(null==token)
            throw new BusinessException(JsonResponseStatus.TOKEN_ERROR);
        //根据token令牌获取存储在redis中的user对象信息
        User user = redisService.getUserByToken(token);
        //判断user是否为空
        if(null==user){
            throw new BusinessException(JsonResponseStatus.TOKEN_ERROR);
        }
        return user;
    }
}
